package com.king.sqlSession;

import com.king.config.BoundSql;
import com.king.pojo.Configuration;
import com.king.pojo.MapperStatement;
import com.king.utils.GenericTokenParser;
import com.king.utils.ParameterMapping;
import com.king.utils.ParameterMappingTokenHandler;

import java.beans.PropertyDescriptor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.sql.*;
import java.util.ArrayList;
import java.util.List;

/**
 * @ClassName: SimpleExecutor
 * @Description: TODO
 * @Author: wangchangyong
 * @Date: 2020/3/26 21:50
 * @Version: 1.0.0
 **/
public class SimpleExecutor implements Executor {

    /**
     * 查询方法
     * @param configuration
     * @param mapperStatement
     * @param params
     * @param <E>
     * @return
     * @throws Exception
     */
    @Override
    public <E> List<E> query(Configuration configuration, MapperStatement mapperStatement, Object... params) throws Exception {
        // 1.获取数据库连接
        Connection connection = configuration.getDataSource().getConnection();

        // 2.获取SQL语句
        String sql = mapperStatement.getSql();
        // 转换SQL语句 #{id} -> ? && id -> 参数值
        BoundSql boundSql = getBoundSql(sql);

        // 3.获取预处理对象：preparedStatement
        PreparedStatement preparedStatement = connection.prepareStatement(boundSql.getSqlText());

        // 4.设置参数
        // 参数类对象
        Class<?> parameterTypeClass = getClassType(mapperStatement.getParameterType());
        // SQL参数集合
        List<ParameterMapping> parameterMappingList = boundSql.getParameterMappingList();
        for (int i = 0; i < parameterMappingList.size(); i++) {
            ParameterMapping parameterMapping = parameterMappingList.get(i);
            // 获取参数名称
            String content = parameterMapping.getContent();
            // 获取参数值
            Field declaredField = parameterTypeClass.getDeclaredField(content);
            declaredField.setAccessible(true);
            Object contentValue = declaredField.get(params[0]);
            // 设置参数
            preparedStatement.setObject(i + 1, contentValue);
        }

        // 5.执行SQL
        ResultSet resultSet = preparedStatement.executeQuery();

        // 返回结果对象
        Class<?> resultTypeClass = getClassType(mapperStatement.getResultType());

        // 6.封装返回结果
        List<Object> list = new ArrayList<>();
        while (resultSet.next()) {
            Object o = resultTypeClass.newInstance();
            ResultSetMetaData metaData = resultSet.getMetaData();
            for (int i = 1; i <= metaData.getColumnCount(); i++) {
                // 字段名
                String columnName = metaData.getColumnName(i);
                // 字段值
                Object value = resultSet.getObject(columnName);
                // 使用内省，数据库和实体映射
                PropertyDescriptor propertyDescriptor = new PropertyDescriptor(columnName, resultTypeClass);
                Method writeMethod = propertyDescriptor.getWriteMethod();
                writeMethod.invoke(o, value);
            }
            list.add(o);
        }
        return (List<E>) list;
    }

    /**
     * 更新方法
     * @param configuration
     * @param mapperStatement
     * @param params
     * @return
     * @throws Exception
     */
    @Override
    public int update(Configuration configuration, MapperStatement mapperStatement, Object... params) throws Exception {
        // 1.获取数据库连接
        Connection connection = configuration.getDataSource().getConnection();

        // 2.获取SQL语句
        String sql = mapperStatement.getSql();
        // 转换SQL语句 #{id} -> ? && id -> 参数值
        BoundSql boundSql = getBoundSql(sql);

        // 3.获取预处理对象：preparedStatement
        PreparedStatement preparedStatement = connection.prepareStatement(boundSql.getSqlText());

        // 4.设置参数
        // 参数类对象
        Class<?> parameterTypeClass = getClassType(mapperStatement.getParameterType());
        // SQL参数集合
        List<ParameterMapping> parameterMappingList = boundSql.getParameterMappingList();
        for (int i = 0; i < parameterMappingList.size(); i++) {
            ParameterMapping parameterMapping = parameterMappingList.get(i);
            // 获取参数名称
            String content = parameterMapping.getContent();
            // 获取参数值
            Field declaredField = parameterTypeClass.getDeclaredField(content);
            declaredField.setAccessible(true);
            Object contentValue = declaredField.get(params[0]);
            // 设置参数
            preparedStatement.setObject(i + 1, contentValue);
        }

        // 5.执行SQL
        int rows = preparedStatement.executeUpdate();

        return rows;
    }

    /**
     * #{id} -> ?
     * 解析id的值进行存储
     * @param sql
     * @return
     */
    private BoundSql getBoundSql(String sql){
        // 标记处理类:配置标记解析器来完成对占位符的解析处理工作
        ParameterMappingTokenHandler parameterMappingTokenHandler = new ParameterMappingTokenHandler();
        GenericTokenParser genericTokenParser = new GenericTokenParser("#{", "}", parameterMappingTokenHandler);
        // 解析出来的sql
        String parserSql = genericTokenParser.parse(sql);
        // #{}里面解析出来的参数名称
        List<ParameterMapping> parameterMappings = parameterMappingTokenHandler.getParameterMappings();

        return new BoundSql(parserSql, parameterMappings);
    }

    private Class<?> getClassType(String className) throws ClassNotFoundException {
        if(className != null){
            Class<?> aClass = Class.forName(className);
            return aClass;
        }
        return null;
    }

}
